<script setup>
import {
    ref,
    computed,
    reactive,
    onMounted,
    toRaw,
    getCurrentInstance,
    watch,
} from "vue";
import { mainStore } from "../store/index";
import { ElMessage, ElMessageBox } from "element-plus";
import sfz2 from "../assets/icon/sfz2.png";
import fwq2 from "../assets/icon/fwq2.png";
import icolj from "../assets/icon/icolj.png";
import ico_qn from "../assets/icon/ico_qn.png";
import api from "../utils/api";
import $fetch from "../utils/request";
const { proxy } = getCurrentInstance();
const { $mapevent } = proxy;
const store = mainStore();
let type = ref(null);
let position = computed(() => {
    let embryo = [];
    if (store.punctuation.position instanceof Array) {
        if (type.value == "stereoscopic") {
            store.punctuation.position.forEach((element) => {
                if (element.length == 2) {
                    embryo.push(element[0].toFixed(6));
                    embryo.push(element[1].toFixed(6));
                }
            });
        } else {
            store.punctuation.position.forEach((element) => {
                embryo.push(element.toFixed(6));
            });
        }
    }
    return embryo;
});
let form = reactive({
    name: null,
    position: toRaw(position.value),
    type: null,
    iconImg: null,
    fontSize: 10,
    fontColor: "rgba(60, 255, 0, 1)",
    borderSize: 0,
    borderColor: "rgba(184, 70, 70, 1)",
    SightDistance: 2000000,
    surround: null,
    frameWidth: 0,
    frameColor: "rgba(255, 30, 16, 1)",
    planeColor: "rgba(255, 215, 0, 0.2)",
    lineWidth: 2,
    lineColor: "rgba(255, 215, 0, 1)",
    stereoscopicColor: "rgba(255, 0, 0, 1)",
});

let options = ref([
    {
        value: 0,
        label: "收费站",
    },
    {
        value: 1,
        label: "服务区",
    },
    {
        value: 2,
        label: "枢纽",
    },
    {
        value: 3,
        label: "互通",
    },
]);
let imgList = ref([
    {
        url: sfz2,
        name: "sfz2",
        id: 0,
    },
    {
        url: fwq2,
        name: "fwq2",
        id: 1,
    },
    {
        url: icolj,
        name: "icolj",
        id: 2,
    },
    {
        url: ico_qn,
        name: "ico_qn",
        id: 3,
    },
]);
let imgIconList = computed(() => {
    return store.imgIconList;
});
let surround = [
    {
        value: 0,
        label: "左边",
    },
    {
        value: 1,
        label: "上边",
    },
    {
        value: 2,
        label: "右边",
    },
];
onMounted(() => {
    // $mapevent.cehis()
});
// let show =
watch(
    computed(() => {
        return store.punctuation.show;
    }),
    (n, o) => {
        type.value = store.punctuation.type;
        if (n && !store.editTag) {
            let localData = localStorage.getItem("punctuation");
            if (!localData) return;
            let temporary = JSON.parse(localData);
            form.name = "";
            if (type.value == "point") {
                form.iconImg = temporary.iconImg;
                form.type = temporary.type;
                form.fontSize = temporary.fontSize;
                form.fontColor = temporary.fontColor;
                form.borderSize = temporary.borderSize;
                form.borderColor = temporary.borderColor;
                form.SightDistance = temporary.SightDistance;
                form.surround = temporary.surround;
            }
        }
    }
);
watch(
    computed(() => {
        return store.tagEntity;
    }),
    (n, o) => {
        if (n) {
            let data = toRaw(store.tagEntity.embryo);
            for (const key in data) {
                if (key != "position") form[key] = data[key];
            }
        } else {
            store.changeEditTag(false);
            store.changePunctuation("show", false);
        }
    }
);

function handleClose() {
    $mapevent.f_ClearEntities(1100);
    $mapevent.f_ClearEntities(1101);
    store.changeEditTag(false);
    store.changePunctuation("show", false);
    store.changeTagEntity(null);
    $mapevent.f_ClearEntities(1101, 0);
}
/**
 * 保存
 */
async function onSubmit() {
    if (!form.name) {
        ElMessage({
            type: "info",
            message: "标点名称不能为空！",
        });
        return;
    } else if (!form.SightDistance) {
        form.SightDistance = 2000000;
    }

    form.position = null;
    if (type.value == "point") {
        if (store.editTag) {
            await api.dropEdit(toRaw(form));
        } else {
            localStorage.setItem("punctuation", JSON.stringify(toRaw(form)));
            await api.dropAdd(toRaw(form));
        }
    } else if (type.value == "polygon") {
        if (store.editTag) await api.plottingEdit(toRaw(form));
        else await api.plottingAdd({ ...toRaw(form), type: 1 });
    } else if (type.value == "stereoscopic") {
        if (store.editTag) await api.stereoscopicEdit(toRaw(form));
        else {
            if (
                store.punctuation.position[0].length == 0 ||
                store.punctuation.position[1].length == 0
            ) {
                ElMessage({
                    type: "info",
                    message: "起始点坐标不完整！",
                });
                return;
            }
            await api.stereoscopicAdd(toRaw(form));
        }
    } else if (type.value == "polyline") {
        if (store.editTag) await api.plottingEdit(toRaw(form));
        else await api.plottingAdd({ ...toRaw(form), type: 0 });
    }
    store.changeGather(false);
    handleClose();
}
/**
 * 预览
 */
function Preview() {
    if (!form.name) {
        ElMessage({
            type: "info",
            message: "标点名称不能为空！",
        });
        return;
    } else if (!form.SightDistance) {
        form.SightDistance = 2000000;
    }
    let embryo = { ...toRaw(form) };
    embryo.position = null;
    if (store.editTag) {
        $mapevent.f_ClearEntities(store.tagEntity.type, store.tagEntity.code);
        embryo = { ...embryo, position: store.tagEntity.embryo.position };
    }
    // console.log(toRaw(form));
    if (type.value == "point") {
        if (!store.editTag)
            localStorage.setItem("punctuation", JSON.stringify(toRaw(form)));
        $mapevent.f_AddIconLabel(embryo, new Date(), 1100);
    } else if (type.value == "polygon")
        $mapevent.drawPolygon(embryo, new Date(), 1100);
    else if (type.value == "stereoscopic") {
        if (
            store.punctuation.position[0].length == 0 ||
            store.punctuation.position[1].length == 0
        ) {
            ElMessage({
                type: "info",
                message: "起始点坐标不完整！",
            });
            return;
        }
        $mapevent.f_Add3DStereoscopic(embryo, new Date(), 1100);
    } else if (type.value == "polyline")
        $mapevent.drawPolylines(embryo, new Date(), 1100);
}
/**
 * 取消
 */
function handl() {
    store.changeGather(false);
    handleClose();
    ElMessage("已取消标点添加！");
}
/**
 * 删除（标点、标绘、立体字）
 */
function erasure() {
    ElMessageBox({
        title: "提示",
        message: "是否确定删除该标绘？",
        showCancelButton: true,
        confirmButtonText: "确定",
        confirmButtonClass: "danger",
        cancelButtonText: "取消",
        beforeClose: (action, instance, done) => {
            if (action === "confirm") {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = "等待...";
                if (store.punctuation.type == "point") {
                    api.dropDelete(store.tagEntity.embryo.id).then((res) => {
                        done();
                        setTimeout(() => {
                            instance.confirmButtonLoading = false;
                        }, 300);
                    });
                } else if (
                    store.punctuation.type == "polygon" ||
                    store.punctuation.type == "polyline"
                )
                    api.plottingDelete(
                        Number(store.tagEntity.embryo.type),
                        store.tagEntity.embryo.id
                    ).then((res) => {
                        done();
                        setTimeout(() => {
                            instance.confirmButtonLoading = false;
                        }, 300);
                    });
                else if (store.punctuation.type == "stereoscopic") {
                    api.stereoscopicDelete(store.tagEntity.embryo.id).then(
                        (res) => {
                            done();
                            setTimeout(() => {
                                instance.confirmButtonLoading = false;
                            }, 300);
                        }
                    );
                }
            } else {
                done();
            }
        },
    })
        .then(() => {
            ElMessage({
                type: "success",
                message: "删除成功！",
            });
            handleClose();
        })
        .catch((err) => {
            console.log(123, err);
            ElMessage({
                type: "info",
                message: "取消删除！",
            });
        });
}
function shanchuimg(id) {
    ElMessageBox({
        title: "提示",
        message: "是否确定删除该标点图标？",
        showCancelButton: true,
        confirmButtonText: "确定",
        confirmButtonClass: "danger",
        cancelButtonText: "取消",
        beforeClose: (action, instance, done) => {
            if (action === "confirm") {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = "等待...";
                $fetch("/mapicon/delete", { id }, "post").then((red) => {
                    if (red.code == 200) {
                        done();
                        setTimeout(() => {
                            instance.confirmButtonLoading = false;
                        }, 300);
                    }
                });
            } else {
                done();
            }
        },
    })
        .then(() => {
            ElMessage({
                type: "success",
                message: "删除成功！",
            });
            store.changeImgIconList();
        })
        .catch((err) => {
            console.log(123, err);
            ElMessage({
                type: "info",
                message: "取消删除！",
            });
        });
}
function uploadFile() {
    let formData = new FormData();
    let filex = document.getElementById(`file`).files;
    for (let index = 0; index < filex.length; index++) {
        if (filex[index].size > 1024 * 1 * 1024) {
            ElMessage({
                type: "info",
                message: "单个文件大小不能超过1M!",
            });
            return;
        }
        if (filex[index].type != "image/png") {
            ElMessage({
                type: "info",
                message: "文件应为.png格式!",
            });
            return;
        }
        formData.append("image", filex[index]);
    }
    ElMessageBox.prompt("请输入图标名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "",
        inputValue: "",
        beforeClose: async (action, instance, done, value) => {
            if (action === "confirm") {
                if (instance.inputValue) {
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = "等待...";
                    formData.append("name", instance.inputValue);
                    console.log(formData.get("image"));
                    $fetch(
                        "/mapicon/insert",
                        formData,
                        "post",
                        localStorage.getItem("token"),
                        "multipart/form-data"
                    ).then((red) => {
                        console.log(red);
                        if (red.code == 200) {
                            done();
                            setTimeout(() => {
                                instance.confirmButtonLoading = false;
                            }, 300);
                        }
                    });
                } else {
                    ElMessage({
                        type: "info",
                        message: "模板单元名称不能为空！",
                    });
                }
            } else {
                done();
            }
        },
    })
        .then(() => {
            ElMessage({
                type: "success",
                message: "保存成功！",
            });
            store.changeImgIconList();
        })
        .catch(() => {});
}
</script>

<template>
    <el-dialog
        id="punctuation"
        v-model="store.punctuation.show"
        :title="store.punctuation.title"
        draggable
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
        <el-form :model="form" label-width="68px">
            <el-form-item label="标点名称">
                <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="坐标" v-if="!store.editTag">
                <el-input v-model="position" disabled />
            </el-form-item>
            <el-form-item label="分类" v-if="store.punctuation.type == 'point'">
                <el-select
                    v-model="form.type"
                    class="m-2"
                    placeholder="请选择分类"
                >
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-row v-if="store.punctuation.type == 'point'">
                <el-col :span="12">
                    <el-form-item label="字号" class="aTinyTot">
                        <el-input-number
                            v-model="form.fontSize"
                            :min="10"
                            :max="32"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="颜色">
                        <el-color-picker v-model="form.fontColor" show-alpha />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="store.punctuation.type == 'point'">
                <el-col :span="12">
                    <el-form-item label="边线宽度" class="aTinyTot">
                        <el-input-number
                            v-model="form.borderSize"
                            :min="0"
                            :max="6"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="边线颜色">
                        <el-color-picker
                            v-model="form.borderColor"
                            show-alpha
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item
                label="标点图标"
                v-if="store.punctuation.type == 'point'"
            >
                <div
                    :class="form.iconImg == embryo.name ? 'active' : ''"
                    class="iconImg"
                    v-for="embryo in imgList"
                    @click="form.iconImg = embryo.name"
                >
                    <img :src="embryo.url" alt="" />
                </div>
                <div
                    :class="form.iconImg == embryo.icon ? 'active' : ''"
                    class="iconImg"
                    v-for="embryo in imgIconList"
                    @click="form.iconImg = embryo.icon"
                    style="width: 29px; height: 37px; position: relative"
                >
                    <div class="sahcnhu" @click="shanchuimg(embryo.id)">x</div>
                    <img
                        style="width: 100%; height: 100%"
                        :src="`http://www.yugaosu.com:18081/zlgs/${embryo.icon}`"
                        alt=""
                    />
                </div>
                <div style="font-size: 12px; color: #00eeff">
                    图标大小为29*37像素,.png格式
                </div>
                <label
                    class="el-button el-button--primary"
                    type="button"
                    for="file"
                    >上传</label
                >
                <input
                    type="file"
                    id="file"
                    name="file"
                    multiple
                    style="display: none"
                    @change="uploadFile"
                />
            </el-form-item>
            <el-form-item
                label="名称环绕"
                v-if="store.punctuation.type == 'point'"
            >
                <el-select
                    v-model="form.surround"
                    class="m-2"
                    placeholder="请选择文字环绕方式"
                >
                    <el-option
                        v-for="item in surround"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-row v-if="store.punctuation.type == 'polyline'">
                <el-col :span="12">
                    <el-form-item label="标线宽度" class="aTinyTot">
                        <el-input-number
                            v-model="form.lineWidth"
                            :min="1"
                            :max="12"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="颜色">
                        <el-color-picker v-model="form.lineColor" show-alpha />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="store.punctuation.type == 'polygon'">
                <el-col :span="12">
                    <el-form-item label="标面边宽" class="aTinyTot">
                        <el-input-number
                            v-model="form.frameWidth"
                            :min="0"
                            :max="1"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="颜色">
                        <el-color-picker v-model="form.frameColor" show-alpha />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item
                label="标面颜色"
                v-if="store.punctuation.type == 'polygon'"
            >
                <el-color-picker v-model="form.planeColor" show-alpha />
            </el-form-item>
            <el-form-item
                label="视距"
                v-if="store.punctuation.type != 'stereoscopic'"
            >
                <el-input-number v-model="form.SightDistance" :min="20000" />
            </el-form-item>
            <el-form-item
                label="颜色"
                v-if="store.punctuation.type == 'stereoscopic'"
            >
                <el-color-picker v-model="form.stereoscopicColor" show-alpha />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">保存</el-button>
                <el-button type="primary" @click="Preview">预览</el-button>
                <el-button
                    v-if="store.editTag"
                    type="primary"
                    class="danger"
                    @click="erasure"
                    >删除</el-button
                >
                <el-button @click="handl">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<style lang="less">
#punctuation {
    position: fixed;
    z-index: 99999;
    width: 450px;
    height: 60%;
    top: 80px;
    right: 130px;
    margin: 0;
    pointer-events: auto;
    border: 2px solid #006699;
    background-color: #00669957;
    transition: right 0.8s ease-out;
    .el-dialog__headerbtn {
        top: -2px;
    }
    .el-tree-node__content {
        color: #fff;
    }
    .el-tree-node__content:hover {
        background-color: #0066998a;
    }
    .el-dialog__header {
        width: calc(100% - 40px);
        padding: 10px 20px;
        background-color: #0066997c;

        .el-dialog__title {
            color: #fff;
            font-size: 16px;
        }
        .el-icon svg {
            color: #fff;
        }
    }
    .el-dialog__body {
        padding-top: 20px;
        padding-bottom: 0;
        height: calc(100% - 20px - 54px - 20px);
        overflow-y: auto;
    }
    .el-form-item__label {
        color: #fff;
    }
    .iconImg {
        margin: 0 4px 0;
        height: 37px;
        cursor: pointer;
        flex-wrap: wrap;
        border: 2px solid transparent;
        border-radius: 4px;
    }
    .active {
        border-color: #00eeff;
    }
    .aTinyTot .el-input-number {
        width: 85px;
    }
    .el-input-number .el-input__wrapper {
        padding: 0 6px;
    }
    .el-input-number .el-input__inner {
        text-align: left;
    }
    .el-input-number__decrease,
    .el-input-number__increase {
        display: none;
    }
    .sahcnhu {
        background-color: red;
        width: 10px;
        height: 10px;
        border-radius: 6px;
        padding: 2px;
        line-height: 10px;
        text-align: center;
        color: #fff;
        position: absolute;
        right: -6px;
        top: -6px;
    }
}
</style>
